<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
     <el-form :inline="true">
        <el-form-item  label="名字">
          <el-input @keyup.enter.native="handleFilter" clearable v-model="listQuery.name" style="width: 200px;" class="filter-item" placeholder="请输入名字">
          </el-input>
        </el-form-item>       
         <el-form-item  label="手机号码">
          <el-input @keyup.enter.native="handleFilter" clearable v-model="listQuery.phone" style="width: 200px;" class="filter-item" placeholder="请输入号码">
          </el-input>
        </el-form-item>    
        <el-form-item  label="代理地区">
          <el-input @keyup.enter.native="handleFilter" clearable v-model="listQuery.agentArea" style="width: 200px;" class="filter-item" placeholder="请输入地区">
          </el-input>
        </el-form-item>              
        <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('common.Search')}}</el-button>
        <el-button type="primary"  v-waves icon="el-icon-circle-plus-outline" class="filter-item" @click="add1">{{$t('common.Add')}}</el-button>
        <el-button class="filter-item" type="primary" v-waves :loading="downloadLoading" @click="handleDownload" icon="el-icon-download">{{$t('common.Export')}}</el-button>
        <el-button  class="filter-item" type='primary' v-waves   icon="el-icon-upload" @click='uploadBtn'  :loading="uploadLoading">{{$t('device.Import')}}</el-button>
      </el-form>       
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column align="center" label="序号" prop="index" />
      <el-table-column align="center" label="手机号" prop="userPhone"/>
      <el-table-column  align="center" label="姓名" prop="userName" />
      <el-table-column  align="center" label="代理地区" prop="agentArea" />
      <el-table-column align="center" label="操作"  class-name="small-padding fixed-width"> 
        <template slot-scope="scope">
           <div class="fx"> 
             <el-button  size="mini" type="danger" @click="del(scope.row.id)">删除</el-button> 
             <el-button  size="mini" type='primary' @click="edit(scope.row)">编辑</el-button>
           </div> 
         </template>
       </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- 添加和编辑弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog.add">
      <el-form  :model="addQuery" :rules='addRules' ref="addDept" label-position="right" label-width="120px" >  
        <el-form-item label="手机号" prop="phone">
          <el-input  :disabled="dialogType == 2" v-model="addQuery.phone" maxlength="11" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType==1">
          <el-input v-model="addQuery.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="姓名" v-if="dialogType==1" prop="name">
          <el-input v-model="addQuery.name"  placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="所在国家">
          <el-radio-group @change="addQuery.agentArea = ''; addressQuery = { agentProvince: '',
              agentCity: '',}" v-model="country">
            <el-radio :label="1">中国</el-radio>
            <el-radio :label="2">澳大利亚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用范围" prop="agentArea">
          <!-- 添加key 让组件重新渲染 -->
          <pcq
            :key="country"
            :level='2' 
            :proviceId='addressQuery.agentProvince' 
            :cityId='addressQuery.agentCity'
            label='NAME'
            :address='address'
            @change='onAddressChange'
          ></pcq>
        </el-form-item>   
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="loading.add" @click="add2" v-if="dialogType == 1">确定</el-button>
        <el-button type="primary" :loading="loading.add" @click="update" v-else>确定</el-button>
        <el-button type="primary"  @click="dialog.add = false">取消</el-button>        
      </div>
    </el-dialog>
    <!-- 导入excel -->
    <input type="file" @change="uploadExcel" ref='uploadExcel' style="display:none">
  </div>
</template>

<script>
import { exportExcel} from '@/api/employee'
import { getAgentsList, delAgent, addAgent,setAgentArea, importingAgent } from '@/api/agent'
import pcq from '@/components/Address'
import { address } from '@/utils/getAddress'
import { Aus } from '@/utils/Australlia'
export default {
  name: 'agent_province',
  components: {
    pcq
  },
  data() {
    return {
      downloadLoading: false,
      uploadLoading: false,
      country: 2,
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        name: '',
        type: 2,
        phone: '',
        agentArea: '',
      },
      dialog: {
        add: false
      },
      loading: {
        list: false,
        add:false
      },
      list: null,
      dialogType: 1,
      addQuery:{
        phone:'',
        type:2 ,
        agentArea: '',
        password: '',
        name: ''
      },
      addRules:{
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' },],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },],
        name: [{ required: true, message: '请输入名字', trigger: 'blur' },],
        agentArea: [{ required: true, message: '请选择省', trigger: 'blur' },],
      },
      id:'',
      addressQuery: {
        agentProvince: '',
        agentCity: '',
      }
      
    }
  },
  created() {
    this.getList()
  },
  watch: {
    addressQuery: {
      deep: true,
      handler (nv, ov) {
        let values = Object.values(nv)
        let is = values.every(item => item)
        if (is) {
          this.addQuery.agentArea = values.join(',')
        } else {
          this.addQuery.agentArea = ''
        }
      }
    }
  },
  computed:{
    dialogTitle () {
      return this.dialogType === 1 ? '新增市代理' : '编辑市代理'
    },
    address () {
      if (this.country === 1) {
        return address
      }
      let temp = Aus.map(item => {
        return {
          ...item,
          AREA_ID: item.id,
          NAME: item.name,
          FID: item.fid
        }
      })
      return temp
    }
  },
  methods: {
    // 导入按钮
    uploadBtn () {
      this.$refs.uploadExcel.click()
    },
    // 上传excel
    async uploadExcel (e) {
      
      this.uploadLoading = true
      try {
        const excel = e.target.files[0]
       
        const fd = new FormData()
        fd.append('excel', excel)
        fd.append('type', 1)
        const res = await importingAgent(fd)
        if (res.code === 1) {
          this.$message.success('导入成功')
          this.getList()
        }
      } catch (error) {
        this.$refs.uploadExcel.value = ''
        this.uploadLoading = false
      }
      this.uploadLoading = false
       this.$refs.uploadExcel.value = ''
    },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '手机号', '姓名','	代理地区']
        const filterVal = ['index', 'userPhone', 'userName','agentArea']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '市代理列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'ctime') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
      }))
    },
    onAddressChange (val) {
      let [agentProvince, agentCity] = val
      this.addressQuery = Object.assign({}, this.addressQuery, {agentProvince, agentCity})
    },
    //获取省代理列表
    async getList() {
      this.loading.list = true
      const { data } = await getAgentsList(this.listQuery)
      this.list = data.records.map((item, index) => ({index: index + 1, ...item}))
      this.total = data.total
      this.loading.list = false     
    },
    //点击新增
    add1(){
     if(this.dialogType == 2){
        this.addQuery = {
          phone:'',
          type:2 ,
          agentArea: '',
          password: '',
          name: ''
         }
        }
      this.dialogType = 1
      this.dialog.add = true
    },
    //点击编辑
    edit(row){
      this.dialog.add = true
      this.dialogType = 2
      this.addQuery.name = row.userName
      this.addQuery.phone = row.userPhone
      this.id = row.id
      let [agentProvince, agentCity] = row.agentArea.split(',')

      this.addressQuery = Object.assign({}, this.addressQuery, {agentProvince, agentCity})
    },
    //点击删除
     async del(id){
       this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(async () => {
        const {data} = await delAgent({id})
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getList()                 
        }).catch(() => {        
        });
    },
    //提交新增
    async add2(){
      this.$refs['addDept'].validate(async (valid) => {
        if (valid) {
          this.loading.add = true
          try {            
              const data = await addAgent(this.addQuery)
              if (data.code == 1) {
                this.$message.success('新增成功')
                this.dialog.add = false
                this.$refs['addDept'].resetFields()
                this.getList()
              }                          
            }catch (error) {            
            }
          this.loading.add = false
        }
      })    
    },
    //提交编辑
    async update(){
      this.$refs['addDept'].validate(async (valid) => {
        if (valid) {
          this.loading.add = true
          try {            
              const data = await setAgentArea({...this.addQuery,id:this.id})
              if (data.code == 1) {
                this.$message.success('编辑成功')
                this.dialog.add = false
                this.$refs['addDept'].resetFields()
                this.getList()
              }                          
            }catch (error) {            
            }
          this.loading.add = false
        }
      })    
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    }
  }
}
</script>
